//
//  UserLocationViewController.m
//  keyboard
//
//  Created by 遇水 on 16/3/12.
//  Copyright © 2016年 遇水. All rights reserved.
//

#import "UserLocationViewController.h"
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>

@interface UserLocationViewController ()<UITableViewDelegate,UITableViewDataSource,MKMapViewDelegate,CLLocationManagerDelegate>

@property (nonatomic, strong) UITableView    *tableView;            //显示位置信息
@property (nonatomic, strong) NSMutableArray    *dataSource;        //存放位置信息

@property (nonatomic, strong) MKMapView  *mapView;             //地图
@property (nonatomic, strong) UIButton    *userLocation;        //显示定位用户位置

@property (nonatomic, strong) NSIndexPath    *selectedIndex;        //当前显示的index

@property (nonatomic, strong) CLLocationManager    *locationManager;        //定位管理器

@property (nonatomic, assign) CLLocationCoordinate2D    userCoordinte; //用户当前的位置坐标

@property (nonatomic, strong) CLGeocoder    *geocoder;          //反地理编码

@end

@implementation UserLocationViewController


-(NSMutableArray *)dataSource{
    if(!_dataSource){
        _dataSource = [NSMutableArray array];
    }
    
    return _dataSource;
}

-(CLGeocoder *)geocoder{
    if(!_geocoder){
        _geocoder = [[CLGeocoder alloc]init];
    }
    
    return _geocoder;
}

- (void)viewDidLoad {
    [super viewDidLoad];
   
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(cancel)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"发送" style:UIBarButtonItemStylePlain target:self action:@selector(sendLocation)];
    
    [self requestLocationServicesEnable];
    [self initSubview];
}


-(void)initSubview
{
    //初始化子控件
    MKMapView *mapView = [MKMapView new];
    mapView.delegate  =self;
    [self.view addSubview:mapView];
    self.mapView  =mapView;
    
    UITableView *tableView = [UITableView new];
    tableView.delegate =self;
    tableView.dataSource =self;
    [self.view addSubview:tableView];
    self.tableView = tableView;
    
    //添加按钮
    UIButton *userLocation = [UIButton buttonWithType:UIButtonTypeCustom];
    [userLocation addTarget:self action:@selector(showUserLocation) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.userLocation = userLocation];
    
}


-(void)updateViewConstraints
{
    [super updateViewConstraints];
    
    //写约束
}


#pragma mark action
-(void)cancel{
    
    //调用代理方法
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(void)sendLocation
{
    NSObject *location = self.dataSource[self.selectedIndex.row];
    [self dismissViewControllerAnimated:YES completion:nil];
    
    
    //调用代理方法
//    if (self.delegate && [self.delegate respondsToSelector:@selector()]) {
//        
//    }
    
}


-(void)showUserLocation
{
    //将用户当前地址显示为中心点

    
}


-(void)updateUserLocation:(CLLocationCoordinate2D)coordinate
{
    //更能用户当前位置为中心点
}

#pragma mark mapViewDelegate
-(void)mapViewDidFinishLoadingMap:(MKMapView *)mapView
{
    [mapView setShowsUserLocation:YES];
}


-(void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated
{

    
}



#pragma mark tableView 
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataSource.count;
}



-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *ID  =@"tableViewCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
        
    }
    
    
    
    return cell;
}



-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    self.selectedIndex = indexPath;
    
}

#pragma private Methods
/**
 *  传入当前用户的位置
 *
 *  @param coordinte
 */
-(void)requestData:(CLLocationCoordinate2D)coordinte
{
    MKCoordinateSpan span = MKCoordinateSpanMake(500, 500);
    MKCoordinateRegion region = MKCoordinateRegionMake(coordinte, span);
    MKLocalSearchRequest *request = [[MKLocalSearchRequest alloc]init];
    request.region = region;
    request.naturalLanguageQuery  =@"";
    
    MKLocalSearch *search = [[MKLocalSearch alloc]initWithRequest:request];
    
    if(![search isSearching]){
        [search startWithCompletionHandler:^(MKLocalSearchResponse * _Nullable response, NSError * _Nullable error) {
            
            NSArray *items = response.mapItems;
            //
            for (MKMapItem *item in items) {
                //反地理编码
                
            }
            
            [self.tableView reloadData];
        }];
    }
}


/**
 *  判断用户是否开启定位功能
 */
-(void)requestLocationServicesEnable
{
    _locationManager = [[CLLocationManager alloc]init];
    if (![CLLocationManager locationServicesEnabled]) {
        return;
    }
    
    if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied) {
        [self.locationManager requestWhenInUseAuthorization];
    }else if([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse){
        self.locationManager.delegate = self;
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        CLLocationDistance distance = 10.0;
        self.locationManager.distanceFilter = distance;
        
        [self.locationManager startUpdatingLocation];
    }
    
    
    
}

#pragma mark llocationManager
-(void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
    if (status == kCLAuthorizationStatusAuthorizedAlways || status == kCLAuthorizationStatusAuthorizedWhenInUse) {
        [manager startUpdatingLocation];
    }
}


-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    CLLocation *location = [locations firstObject];
    self.userCoordinte = location.coordinate;
    
    //停止定位
    [self.locationManager stopUpdatingLocation];
}



//地理编码
-(CLPlacemark *)gepcode:(NSString *)address
{
    __block CLPlacemark *placemark;
    [self.geocoder geocodeAddressString:address completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        if (error) {
            return ;
        }
        if (placemarks) {
            placemarks = (CLPlacemark *)[placemarks firstObject];
        }
    }];
    
    return placemark;
}


//反地理编码
-(void)getAddressByLatitude:(CLLocationDegrees)latitude longitude:(CLLocationDegrees)longitude{
    //反地理编码
    CLLocation *location=[[CLLocation alloc]initWithLatitude:latitude longitude:longitude];
    [_geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
        CLPlacemark *placemark=[placemarks firstObject];
        NSLog(@"详细信息:%@",placemark.addressDictionary);
    }];
}



@end
